package com.chen.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.dto.LogInAndRegisterDto;
import com.chen.entity.User;
import com.chen.mapper.UserMapper;
import com.chen.service.TokenService;
import com.chen.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.utils.JWTUtils;
import com.chen.utils.RedisUtil;
import com.chen.vo.CustomException;
import com.chen.vo.ErrorCode;
import com.chen.vo.Result;
import com.chen.vo.UserVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author cws
 * @since 2024-11-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String slat = "mszlu!@#";

    @Autowired
    UserService sysUserService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @Autowired
    UserMapper sysUserMapper;

    @Autowired
    RedisUtil redisUtil;


    @Autowired
    private TokenService tokenService;

    @Override
    public Result login(LogInAndRegisterDto loginParams) {
        String account = loginParams.getUsername();
        String password = loginParams.getPassword();
//       判断账号密码时候为空
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
//加密
        String pwd = DigestUtils.md5Hex(password + slat);

//      查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, account).eq(User::getPassword, pwd).last("limit 1");
        User sysUser = sysUserService.getOne(wrapper);
//如果为空直接返回状态码
        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        if (sysUser.getStatus().equals(0)) {
            return Result.fail(ErrorCode.ACCOUNT_LOCKED.getCode(), ErrorCode.ACCOUNT_LOCKED.getMsg());
        }
//        根据id生成token
        String token = JWTUtils.createToken(sysUser.getId());

//        存放到redis
        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
//        将token存入redis 1个小时
        redisUtil.set("TOKEN:" + token, token, 3600);
        return Result.success(token);

    }

    @Override
    public Result register(LogInAndRegisterDto loginParams) {
        String account = loginParams.getUsername();
        String password = loginParams.getPassword();
//       判断账号密码时候为空
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
//      查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, account);
        int count = sysUserService.count(wrapper);
        if (count > 0) {
            throw new CustomException(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        //加密
        String pwd = DigestUtils.md5Hex(password + slat);
        User user = new User();
        user.setUsername(account);
        user.setPassword(pwd);
        user.setNickname(account);
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setIcon("https://blog-chen.oss-cn-shanghai.aliyuncs.com/bolg/music/2022-10-10/Snipaste_2022-10-10_13-51-27.png");
        user.setGender(0);
        sysUserMapper.insert(user);
        return Result.success();
    }

    @Override
    public Result getUserInfo(String token) {
        User userToken = tokenService.checkToken(token);
        //           校验token是否为空
        if (userToken == null) {
            return Result.fail(ErrorCode.NO_TOKEN.getCode(), ErrorCode.NO_TOKEN.getMsg());
        }
        UserVo userVo = new UserVo();
        User user = baseMapper.selectById(userToken.getId());
        BeanUtils.copyProperties(user, userVo);
        return Result.success(userVo);
    }

    @Override
    public boolean updateAmout(Long userId, BigDecimal bigDecimal) {

        return sysUserMapper.updateAmout(userId, bigDecimal);
    }

    @Override
    public boolean updateIntegration(Long userId, Integer integration) {
        return sysUserMapper.updateIntegration(userId, integration)==1?true:false;
    }


}
